#include "databasewindow.h"
#include "ui_databasewindow.h"
#include "deviceinfowindow.h"
#include <QDateTime>
#include <QDebug>
#include <QMessageBox>
#include <QInputDialog>
#include <QCloseEvent>
#include <QHeaderView>
#include <QTableWidgetItem>

DatabaseWindow::DatabaseWindow(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::DatabaseWindow)
    , hasUnsavedChanges(false)
    , database(new Database(this))
{
    ui->setupUi(this);
    
    // 设置窗口属性
    setWindowFlags(Qt::Window | Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint);
    setWindowTitle("数据库管理");
    resize(800, 600);
    
    // 连接信号和槽
    connect(ui->tableComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &DatabaseWindow::onTableChanged);
    connect(ui->addButton, &QPushButton::clicked, this, &DatabaseWindow::onAddClicked);
    connect(ui->editButton, &QPushButton::clicked, this, &DatabaseWindow::onEditClicked);
    connect(ui->deleteButton, &QPushButton::clicked, this, &DatabaseWindow::onDeleteClicked);
    connect(ui->deviceInfoButton, &QPushButton::clicked, this, &DatabaseWindow::onDeviceInfoClicked);
    connect(ui->refreshButton, &QPushButton::clicked, this, &DatabaseWindow::onRefreshClicked);
    connect(ui->saveButton, &QPushButton::clicked, this, &DatabaseWindow::onSaveClicked);
    connect(ui->closeButton, &QPushButton::clicked, this, &DatabaseWindow::onCloseClicked);
    
    // 连接表格变化信号
    connect(ui->dataTableWidget, &QTableWidget::cellChanged, this, &DatabaseWindow::onCellChanged);
    
    // 初始化数据库
    initializeDatabase();
    
    // 设置表格属性
    ui->dataTableWidget->setAlternatingRowColors(true);
    ui->dataTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->dataTableWidget->setSortingEnabled(false); // 禁用排序以避免数据混乱
    
    // 设置表格自适应大小
    ui->dataTableWidget->horizontalHeader()->setStretchLastSection(true); // 最后一列自动拉伸
    ui->dataTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); // 允许手动调整列宽
    ui->dataTableWidget->verticalHeader()->setVisible(false); // 隐藏行号
    ui->dataTableWidget->setWordWrap(true); // 允许文本换行
    
    // 加载数据
    loadData();
    
    // 更新状态
    updateStatus();
}

DatabaseWindow::~DatabaseWindow()
{
    delete ui;
}

void DatabaseWindow::initializeDatabase()
{
    if (!database->initializeDatabase()) {
        QMessageBox::critical(this, "数据库错误", 
                            QString("无法初始化数据库: %1").arg(database->getLastError()));
    }
}

void DatabaseWindow::loadData()
{
    QList<Product> products = database->getAllProducts();
    
    ui->dataTableWidget->setRowCount(products.size());
    ui->dataTableWidget->setColumnCount(8);
    
    // 设置表头
    QStringList headers;
    headers << "ID" << "商品名称" << "分类" << "库存数量" << "单价(元)" << "状态" << "录入时间" << "最后更新时间";
    ui->dataTableWidget->setHorizontalHeaderLabels(headers);
    
    // 填充数据
    for (int i = 0; i < products.size(); ++i) {
        setProductToRow(i, products[i]);
    }
    
    // 调整列宽
    ui->dataTableWidget->resizeColumnsToContents();
    ui->dataTableWidget->horizontalHeader()->setStretchLastSection(true);
    
    hasUnsavedChanges = false;
}

void DatabaseWindow::refreshTable()
{
    loadData();
    updateStatus();
}

void DatabaseWindow::updateStatus()
{
    int rowCount = ui->dataTableWidget->rowCount();
    QString statusText = QString("共 %1 条记录").arg(rowCount);
    
    if (hasUnsavedChanges) {
        statusText += " | 有未保存的更改";
        ui->saveButton->setEnabled(true);
    } else {
        statusText += " | 数据已保存";
        ui->saveButton->setEnabled(false);
    }
    
    ui->statusLabel->setText(statusText);
    ui->recordCountLabel->setText(QString("记录数: %1").arg(rowCount));
}

Product DatabaseWindow::getProductFromRow(int row)
{
    Product product;
    
    if (row < 0 || row >= ui->dataTableWidget->rowCount()) {
        return product;
    }
    
    QTableWidgetItem* idItem = ui->dataTableWidget->item(row, 0);
    if (idItem) {
        product.id = idItem->text().toInt();
    }
    
    QTableWidgetItem* nameItem = ui->dataTableWidget->item(row, 1);
    if (nameItem) {
        product.name = nameItem->text();
    }
    
    QTableWidgetItem* categoryItem = ui->dataTableWidget->item(row, 2);
    if (categoryItem) {
        product.category = categoryItem->text();
    }
    
    QTableWidgetItem* stockItem = ui->dataTableWidget->item(row, 3);
    if (stockItem) {
        product.stock = stockItem->text().toInt();
    }
    
    QTableWidgetItem* priceItem = ui->dataTableWidget->item(row, 4);
    if (priceItem) {
        product.price = priceItem->text().toDouble();
    }
    
    QTableWidgetItem* statusItem = ui->dataTableWidget->item(row, 5);
    if (statusItem) {
        product.status = statusItem->text();
    }
    
    QTableWidgetItem* createdTimeItem = ui->dataTableWidget->item(row, 6);
    if (createdTimeItem) {
        product.createdTime = QDateTime::fromString(createdTimeItem->text(), "yyyy-MM-dd hh:mm:ss");
    }
    
    QTableWidgetItem* updatedTimeItem = ui->dataTableWidget->item(row, 7);
    if (updatedTimeItem) {
        product.updatedTime = QDateTime::fromString(updatedTimeItem->text(), "yyyy-MM-dd hh:mm:ss");
    }
    
    return product;
}

void DatabaseWindow::setProductToRow(int row, const Product& product)
{
    // 临时断开信号连接以避免触发cellChanged
    ui->dataTableWidget->blockSignals(true);
    
    ui->dataTableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(product.id)));
    ui->dataTableWidget->setItem(row, 1, new QTableWidgetItem(product.name));
    ui->dataTableWidget->setItem(row, 2, new QTableWidgetItem(product.category));
    ui->dataTableWidget->setItem(row, 3, new QTableWidgetItem(QString::number(product.stock)));
    ui->dataTableWidget->setItem(row, 4, new QTableWidgetItem(QString::number(product.price, 'f', 2)));
    ui->dataTableWidget->setItem(row, 5, new QTableWidgetItem(product.status));
    ui->dataTableWidget->setItem(row, 6, new QTableWidgetItem(product.createdTime.toString("yyyy-MM-dd hh:mm:ss")));
    ui->dataTableWidget->setItem(row, 7, new QTableWidgetItem(product.updatedTime.toString("yyyy-MM-dd hh:mm:ss")));
    
    // ID列设为只读
    ui->dataTableWidget->item(row, 0)->setFlags(ui->dataTableWidget->item(row, 0)->flags() & ~Qt::ItemIsEditable);
    // 时间列设为只读
    ui->dataTableWidget->item(row, 6)->setFlags(ui->dataTableWidget->item(row, 6)->flags() & ~Qt::ItemIsEditable);
    ui->dataTableWidget->item(row, 7)->setFlags(ui->dataTableWidget->item(row, 7)->flags() & ~Qt::ItemIsEditable);
    
    ui->dataTableWidget->blockSignals(false);
}

void DatabaseWindow::saveChanges()
{
    if (!hasUnsavedChanges) {
        return;
    }
    
    // 遍历所有行，更新数据库
    for (int row = 0; row < ui->dataTableWidget->rowCount(); ++row) {
        Product product = getProductFromRow(row);
        if (product.id > 0) {
            if (!database->updateProduct(product)) {
                QMessageBox::warning(this, "保存失败", 
                                   QString("更新商品失败: %1").arg(database->getLastError()));
                return;
            }
        }
    }
    
    hasUnsavedChanges = false;
    updateStatus();
    
    // 重新加载数据以获取最新的时间戳
    refreshTable();
    
    QMessageBox::information(this, "保存成功", "数据已成功保存到数据库！");
}

void DatabaseWindow::onTableChanged(int index)
{
    Q_UNUSED(index)
    // 当前只有一个表，暂时不需要处理
    refreshTable();
}

void DatabaseWindow::onAddClicked()
{
    bool ok;
    QString name = QInputDialog::getText(this, "添加商品", "商品名称:", QLineEdit::Normal, "", &ok);
    if (!ok || name.isEmpty()) {
        return;
    }
    
    QString category = QInputDialog::getText(this, "添加商品", "商品分类:", QLineEdit::Normal, "", &ok);
    if (!ok || category.isEmpty()) {
        return;
    }
    
    int stock = QInputDialog::getInt(this, "添加商品", "库存数量:", 0, 0, 9999, 1, &ok);
    if (!ok) {
        return;
    }
    
    double price = QInputDialog::getDouble(this, "添加商品", "单价(元):", 0.0, 0.0, 999.99, 2, &ok);
    if (!ok) {
        return;
    }
    
    QStringList statusList;
    statusList << "在售" << "售罄" << "下架" << "促销";
    QString status = QInputDialog::getItem(this, "添加商品", "状态:", statusList, 0, false, &ok);
    if (!ok) {
        return;
    }
    
    Product product(0, name, category, stock, price, status);
    
    if (database->addProduct(product)) {
        refreshTable();
        QMessageBox::information(this, "添加成功", "商品已成功添加！");
    } else {
        QMessageBox::warning(this, "添加失败", 
                           QString("添加商品失败: %1").arg(database->getLastError()));
    }
}

void DatabaseWindow::onEditClicked()
{
    int currentRow = ui->dataTableWidget->currentRow();
    if (currentRow < 0) {
        QMessageBox::information(this, "提示", "请选择要编辑的商品行！");
        return;
    }
    
    QMessageBox::information(this, "编辑提示", "请直接在表格中双击单元格进行编辑，编辑完成后点击保存按钮。");
}

void DatabaseWindow::onDeleteClicked()
{
    int currentRow = ui->dataTableWidget->currentRow();
    if (currentRow < 0) {
        QMessageBox::information(this, "提示", "请选择要删除的商品行！");
        return;
    }
    
    QTableWidgetItem* idItem = ui->dataTableWidget->item(currentRow, 0);
    QTableWidgetItem* nameItem = ui->dataTableWidget->item(currentRow, 1);
    
    if (!idItem || !nameItem) {
        return;
    }
    
    int id = idItem->text().toInt();
    QString name = nameItem->text();
    
    int ret = QMessageBox::question(this, "确认删除", 
                                  QString("确定要删除商品 \"%1\" 吗？\n此操作不可撤销！").arg(name),
                                  QMessageBox::Yes | QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        if (database->deleteProduct(id)) {
            refreshTable();
            QMessageBox::information(this, "删除成功", "商品已成功删除！");
        } else {
            QMessageBox::warning(this, "删除失败", 
                               QString("删除商品失败: %1").arg(database->getLastError()));
        }
    }
}

void DatabaseWindow::onDeviceInfoClicked()
{
    DeviceInfoWindow *deviceWindow = new DeviceInfoWindow(this);
    deviceWindow->show();
}

void DatabaseWindow::onRefreshClicked()
{
    if (hasUnsavedChanges) {
        int ret = QMessageBox::question(this, "确认刷新", 
                                      "刷新将丢失未保存的更改，确定要继续吗？",
                                      QMessageBox::Yes | QMessageBox::No);
        if (ret != QMessageBox::Yes) {
            return;
        }
    }
    
    refreshTable();
    QMessageBox::information(this, "刷新完成", "数据已刷新！");
}

void DatabaseWindow::onSaveClicked()
{
    saveChanges();
}

void DatabaseWindow::onCloseClicked()
{
    close();
}

void DatabaseWindow::onCellChanged(int row, int column)
{
    Q_UNUSED(row)
    Q_UNUSED(column)
    
    hasUnsavedChanges = true;
    updateStatus();
}

void DatabaseWindow::closeEvent(QCloseEvent *event)
{
    if (hasUnsavedChanges) {
        int ret = QMessageBox::question(this, "确认关闭", 
                                      "有未保存的更改，确定要关闭吗？",
                                      QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        
        if (ret == QMessageBox::Save) {
            saveChanges();
            emit windowClosed();
            event->accept();
        } else if (ret == QMessageBox::Discard) {
            emit windowClosed();
            event->accept();
        } else {
            event->ignore();
        }
    } else {
        emit windowClosed();
        event->accept();
    }
}